#include "csv.h"
#include <fstream>
#include <sstream>
#include <algorithm>
using namespace std;
string trim(string str) {
    str.erase(remove_if(str.begin(), str.end(), ::isspace), str.end());
    return str;
}
csv::csv(string filePath) {
    this->filePath = filePath;
}
bool csv::parse() {
    ifstream file(this->filePath);
    if (!file.is_open()) {
        return false;
    }
    string line;
    while (getline(file, line)) {
        line = trim(line);
        vector<string> row;
        stringstream ss(line);
        string cell;
        while (getline(ss, cell, ',')) {
            row.push_back(cell);
        }
        if (row.size() < this->getCols()) {
            for (int i = 0; i < this->getCols() - row.size(); i++) {
                row.push_back("");
            }
        }
        this->data.push_back(row);
    }
    file.close();
    return true;
}
vector<string> csv::getRow(int i) {
    return this->data[i];
}
vector<string> csv::getCol(int i) {
    vector<string> col;
    for (auto row : this->data) {
        col.push_back(row[i]);
    }
    return col;
}
Size csv::getColIndex(int rowIndex, string item) {
    if (rowIndex >= this->getRows()) {
        return -1;
    }
    for (int i = 0; i < this->getCols(); i++) {
        if (this->data[rowIndex][i] == item) {
            return i;
        }
    }
    return -1;
}
vector<string> csv::getRow(int colIndex, string item) {
    vector<string> row;
    if (colIndex >= this->getCols()) {
        return row;
    }
    for (auto r : this->data) {
        if (r[colIndex] == item) {
            row = r;
            break;
        }
    }
    return row;
}
string csv::getCell(int row, int col) {
    return this->data[row][col];
}
vector<vector<string>> csv::getData() {
    return this->data;
}
Size csv::getRows() {
    return this->data.size();
}
Size csv::getCols() {
    if (this->getRows() > 0) {
        return this->data[0].size();
    } else {
        return 0;
    }
}